package com.baitiaojun.xss.core.filter;

import com.baitiaojun.common.enums.impl.HttpMethodEnums;
import com.baitiaojun.common.utils.string.StringUtils;
import com.baitiaojun.xss.config.XssProperties;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

public class ServletRequestXssFilter extends OncePerRequestFilter {

    private final XssProperties xssProperties;

    public ServletRequestXssFilter(XssProperties xssProperties) {
        this.xssProperties = xssProperties;
    }

    /**
     * 每次请求都会执行doFilter
     * @param request
     * @param response
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        filterChain.doFilter(new ServletRequestXssWrapper(request), response);
    }

    /**
     * 执行shouldNotFilter方法,使用路径匹配器与url匹配的路径不进行过滤
     * @param request
     * @return
     * @throws ServletException
     */
    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) {
        List<String> excludesUrl = xssProperties.getExcludesUrl();
        if (!xssProperties.getEnable()) {
            return false;
        }
        String method = request.getMethod();
        String requestURI = request.getRequestURI();
        requestURI = requestURI.replace(request.getContextPath(), "");
        if (method == null || method.equals(HttpMethodEnums.GET.getName()) || method.equals(HttpMethodEnums.DELETE.getName())) {
            return false;
        }
        return StringUtils.matchAll(excludesUrl, requestURI);
    }
}
